// utils/mediaPreview.tsx
import { createRoot } from 'react-dom/client'
import MediaPreview, {
  type MediaPreviewTyep,
  MediaPreviewTyepList,
} from '@/components/MediaPreview'

export type { MediaPreviewTyep }
export { MediaPreviewTyepList }
export interface MediaInfo {
  type: MediaPreviewTyep
  url: string
  title?: string
}

class MediaPreviewUtil {
  private container: HTMLDivElement | null = null
  private root: any | null = null

  private createContainer() {
    if (!this.container) {
      this.container = document.createElement('div')
      this.container.id = 'media-preview-container'
      document.body.appendChild(this.container)
      this.root = createRoot(this.container)
    }
  }

  public preview = (mediaInfo: MediaInfo) => {
    this.createContainer()

    const handleClose = () => {
      if (this.root) {
        this.root.render(null)
      }
    }

    this.root?.render(
      <MediaPreview open={true} onClose={handleClose} {...mediaInfo} />,
    )
  }

  public destroy = () => {
    if (this.root) {
      this.root.unmount()
      this.root = null
    }
    if (this.container && this.container.parentNode) {
      this.container.parentNode.removeChild(this.container)
      this.container = null
    }
  }
}

// 导出单例实例
export const mediaPreview = new MediaPreviewUtil()

// 导出便捷方法
export const preview = (mediaInfo: MediaInfo) => mediaPreview.preview(mediaInfo)

// 更简单的版本
export const previewMedia = (() => {
  let container: HTMLDivElement | null = null
  let root: any | null = null

  return (mediaInfo: MediaInfo) => {
    if (!container) {
      container = document.createElement('div')
      document.body.appendChild(container)
      root = createRoot(container)
    }

    const handleClose = () => {
      root?.render(null)
    }

    root?.render(<MediaPreview open={true} onClose={handleClose} {...mediaInfo} />)
  }
})()

// 在任何组件中使用

// function MyComponent() {
//   const handlePreview = () => {
//     preview({
//       type: 'video',
//       url: '/path/to/video.mp4',
//       title: '示例视频',
//     })
//   }

//   return <button onClick={handlePreview}>预览视频</button>
// }
